package com.bullsora.kindlerss.integration

import com.the6hours.grails.springsecurity.facebook.FacebookAuthToken

import com.bullsora.kindlerss.model.AppUser
import org.springframework.social.facebook.api.impl.FacebookTemplate

class FacebookAuthService {

  void prepopulateAppUser(AppUser person, FacebookAuthToken token) {
    def template = new FacebookTemplate(token.accessToken.accessToken)

    populateTimeZone(template, person)

    person.username = template.userOperations().getUserProfile().email
    person.linkedWithFacebook = true
    person.enabled = true
    person.accountExpired = false
    person.accountLocked = false
    person.passwordExpired = false
    person.password = token.accessToken.accessToken
  }

  private def populateTimeZone(FacebookTemplate template, AppUser person) {
    def timezoneOffset = template.userOperations().getUserProfile().timezone
    if (timezoneOffset) {
      if (timezoneOffset > 0) {
        person.timeZone = "UTC+${timezoneOffset}"
      }
      else if (timezoneOffset < 0) {
        person.timeZone = "UTC${timezoneOffset}"
      }
      else {
        person.timeZone = "UTC"
      }
    }
  }
}
